package com.agent.vpsserver.modules.server.client;

import com.agent.vpsserver.common.enmus.EActiveSmsServiceType;
import com.agent.vpsserver.common.enmus.ESMSActivateClientStatus;
import com.agent.vpsserver.common.enmus.ESMSActivateGetStatusActivation;
import com.agent.vpsserver.common.exception.BusinessException;
import com.agent.vpsserver.common.utils.http.HttpClientPoolUtil;
import com.agent.vpsserver.modules.server.client.response.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户账号信息(UserAccount)表服务实现类
 * https://sms-activate.org/cn/api2#prices
 * @author guochao
 * @since 2024-03-12 23:50:24
 */
@Slf4j
@Component
public class ActiveSmsClient {
    private static final String API_KEY = "91dc1e308be49f3d0985bfc6beffAdcd";
    private static final String BASE_URL = "https://api.sms-activate.org/stubs/handler_api.php";

    public SMSActivateGetPricesResponse getPricesByCountryIdAndServiceShortName(EActiveSmsServiceType serviceType) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("api_key", API_KEY);
        paramMap.put("service", serviceType.getType());
        paramMap.put("action", "getPrices");
        log.info("获取价格，params:{}", JSON.toJSONString(paramMap));
        String responseStr = HttpClientPoolUtil.sendGet(BASE_URL, paramMap);
        log.info("获取价格，response:{}", responseStr);
        Map<String, Map<String, SMSActivatePriceInfoResponse>> map = JSON.parseObject(responseStr, new TypeReference<Map<String, Map<String, SMSActivatePriceInfoResponse>>>() {
        });
        return new SMSActivateGetPricesResponse(map);
    }

    public SMSActivateActivationResponse getNumber(String countryId, EActiveSmsServiceType serviceType, String operator) {
        // 没有国家编码则自动取最便宜的
        if (countryId == null) {
            SMSActivateGetPricesResponse pricesByCountryIdAndServiceShortName = this.getPricesByCountryIdAndServiceShortName(serviceType);
            Map<String, Map<String, SMSActivatePriceInfoResponse>> smsActivateGetPriceMap = pricesByCountryIdAndServiceShortName.getSmsActivateGetPriceMap();
            Integer minPrice = null;
            for (Map.Entry<String, Map<String, SMSActivatePriceInfoResponse>> entry : smsActivateGetPriceMap.entrySet()) {
                String id = entry.getKey();
                for (SMSActivatePriceInfoResponse priceInfo : entry.getValue().values()) {
                    if (priceInfo.getCost() == 0) {
                        continue;
                    }
                    if (minPrice == null || priceInfo.getCost().compareTo(minPrice) < 0) {
                        minPrice = priceInfo.getCost();
                        countryId = id;
                    }
                }
            }
        }
        return this.getNumberV2(countryId, serviceType, operator);
    }

    public SMSActivateActivationResponse getNumberV2(String countryId, EActiveSmsServiceType serviceType, String operator) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("api_key", API_KEY);
        paramMap.put("service", serviceType.getType());
        paramMap.put("action", "getNumberV2");
        paramMap.put("country", countryId);
        paramMap.put("operator", operator);
        log.info("激活手机，params:{}", JSON.toJSONString(paramMap));
        String responseStr = HttpClientPoolUtil.sendGet(BASE_URL, paramMap);
        log.info("激活手机，response:{}", responseStr);
        return JSON.parseObject(responseStr, SMSActivateActivationResponse.class);
    }

    public String getStatus(String activationId) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("api_key", API_KEY);
        paramMap.put("id", activationId);
        paramMap.put("action", "getStatus");
        log.info("查询激活状态，params:{}", JSON.toJSONString(paramMap));
        String responseStr = HttpClientPoolUtil.sendGet(BASE_URL, paramMap);
        log.info("查询激活状态，response:{}", responseStr);
        if (responseStr.startsWith(ESMSActivateGetStatusActivation.OK.getResponse())) {
            return responseStr.split(":")[1];
        }
        return null;
    }

    public ESMSActivateGetStatusActivation setStatus(String activationId, ESMSActivateClientStatus status) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("api_key", API_KEY);
        paramMap.put("id", activationId);
        paramMap.put("action", "setStatus");
        paramMap.put("status", String.valueOf(status.getId()));
        log.info("修改激活状态，params:{}", JSON.toJSONString(paramMap));
        String responseStr = HttpClientPoolUtil.sendGet(BASE_URL, paramMap);
        log.info("修改激活状态，response:{}", responseStr);
        ESMSActivateGetStatusActivation statusByName = ESMSActivateGetStatusActivation.getStatusByName(responseStr);
        if (!statusByName.equals(ESMSActivateGetStatusActivation.CANCEL)) {
            throw new BusinessException("取消号码失败");
        }
        return statusByName;
    }

    public Map<String, SMSActivateGetCountryResponse> getCountry() {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("api_key", API_KEY);
        paramMap.put("action", "getCountries");
        log.info("获取国家列表，params:{}", JSON.toJSONString(paramMap));
        String responseStr = HttpClientPoolUtil.sendGet(BASE_URL, paramMap);
        log.info("获取国家列表，response:{}", responseStr);
        return JSON.parseObject(responseStr, new TypeReference<Map<String, SMSActivateGetCountryResponse>>() {
        });
    }

    public Map<String, SMSActivateGetTopCountriesResponse> getTopCountriesByService(EActiveSmsServiceType serviceType) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("api_key", API_KEY);
        paramMap.put("action", "getTopCountriesByService");
        paramMap.put("service", serviceType.getType());
        log.info("获取支持服务的国家列表，params:{}", JSON.toJSONString(paramMap));
        String responseStr = HttpClientPoolUtil.sendGet(BASE_URL, paramMap);
        log.info("获取支持服务的国家列表，response:{}", responseStr);
        return JSON.parseObject(responseStr, new TypeReference<Map<String, SMSActivateGetTopCountriesResponse>>() {
        });
    }

    public List<String> getOperator(String countryId) {
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("api_key", API_KEY);
            paramMap.put("action", "getOperators");
            paramMap.put("country", countryId);
            log.info("获取运营商列表，params:{}", JSON.toJSONString(paramMap));
            String responseStr = HttpClientPoolUtil.sendGet(BASE_URL, paramMap);
            log.info("获取运营商列表，response:{}", responseStr);
            JSONObject jsonObject = JSON.parseObject(responseStr);
            if (!jsonObject.getString("status").equalsIgnoreCase("success")) {
                return Collections.emptyList();
            }
            Object countryOperators = jsonObject.get("countryOperators");
            if (countryOperators instanceof JSONArray) {
                return jsonObject.getJSONArray("countryOperators").getJSONArray(0).toJavaList(String.class);
            }
            Map<String, List<String>> countryOperatorMap = jsonObject.getObject("countryOperators", new TypeReference<Map<String, List<String>>>() {
            });
            return countryOperatorMap.get(countryId);
        } catch (Exception e) {
            log.info("获取运营商列表异常", e);
            return Collections.emptyList();
        }
    }
}
